//
//  MCMyPlanVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/19.
//

import UIKit
import QMUIKit
import SnapKit
import Toast_Swift
import ObjectMapper


class MCMyPlanVc: MCBaseVc {
    
    let myPlanTableViewIdentifier = "myPlanTableViewIdentifier"
    let myPlanCollectionViewIdentifier = "myPlanCollectionViewIdentifier"
    
    
    @IBOutlet weak var myPlanCollectionView: UICollectionView!
    @IBOutlet weak var myPlanTableView: UITableView!
    
    @IBOutlet weak var createPlanButton: UIButton!
    @IBOutlet weak var addPlanButton: UIButton!
    //日历
    var dateCalendar:NSCalendar!
    
    //当前日期
    var dateNow:Date!
    
    
    //月
    var monthCalendar:NSCalendar!
    
    //天
    var dayCalendar:NSCalendar!
    
    //年
    var yearCalendear:NSCalendar!
    
    
    private var dateDataSource:Array<HomeTodayListModel?> = [HomeTodayListModel?]()
    
    private var selectDate:String = ""
    
    private var selectedCollectionItemIndexPath: IndexPath?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        createPlanButton.layoutIfNeeded()
        createPlanButton.layer.cornerRadius = createPlanButton.frame.height / 2
        createPlanButton.layer.borderColor = UIColor.pg_color(withHexString: "#10151C").cgColor
        createPlanButton.layer.borderWidth = 1
        
        addPlanButton.layoutIfNeeded()
        addPlanButton.layer.cornerRadius = createPlanButton.frame.height / 2
        addPlanButton.backgroundColor = UIColor.pg_color(withHexString: "#35DE94")
        
        dateNow = Date.init()
        dateCalendar = NSCalendar.init(calendarIdentifier: .gregorian)
        dateCalendar = NSCalendar.current as NSCalendar
        let timeZone = TimeZone(identifier: "Asia/Shanghai")
        dateCalendar.timeZone = timeZone!
        
        let myPlanCollectionViewLayout = UICollectionViewFlowLayout.init()
        myPlanCollectionViewLayout.scrollDirection = .horizontal
        self.myPlanCollectionView.dataSource = self
        self.myPlanCollectionView.delegate = self
        self.myPlanCollectionView.setCollectionViewLayout(myPlanCollectionViewLayout, animated: true)
        self.myPlanCollectionView.register(UINib(nibName: "MCMyPlanCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: myPlanCollectionViewIdentifier)
        self.myPlanCollectionView.showsHorizontalScrollIndicator = false
        self.myPlanCollectionView.showsVerticalScrollIndicator = false
        
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        
        
        
        self.myPlanTableView.dataSource = self
        self.myPlanTableView.delegate = self
        self.myPlanTableView.rowHeight = 84
        self.myPlanTableView.register(UINib.init(nibName: "MCProgressTableCell", bundle: Bundle.main), forCellReuseIdentifier: myPlanTableViewIdentifier)
        self.myPlanTableView.sectionFooterHeight = 0.1
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.qmui_item(withTitle: "我创建的计划", target:self, action: #selector(createNavigationPush))
        
       
        
    }
    
    //日
    func getDays(_ section: Int) -> Int {
        if getmonths() == 12 {
            if section == 1 {
                let daysnexts =  Date.jk.monthOfDays(month: section + 1)
                return daysnexts
            }else{
                let daysnexts =  Date.jk.monthOfDays(month:  getmonths() + section)
                return daysnexts
            }
        }else {
            
            let daysnexts =  Date.jk.monthOfDays(month: getmonths() + section)
            
            let timeModel:Dictionary<String,Any> = ["years":getYears(),"months":(getmonths() + section),"days":(daysnexts + getweekDay(section:section)),"weakDay":getweekDay(section:section)]
            
            let dayMonthsModel = MCDayMonthsYearModl(JSON: timeModel)
            
          //  self.monthDataSource.append(dayMonthsModel)
            
            return daysnexts
        
        }
    }
    
    //月
    func getmonths() -> Int {
        let months = dateCalendar.component(NSCalendar.Unit.month, from: Date.jk.currentDate)
        return months
    }
    
    //年
    func getYears() -> Int {
        let years = dateCalendar.component(NSCalendar.Unit.year, from: Date.jk.currentDate)
        return years
    }
    
    
    //周
    func getweekDay(section:Int) -> Int {
        
        var weakDay = dateCalendar.components([.era,.year,.month,.day], from: Date.jk.currentDate)
        weakDay.day = 1
        weakDay.month = getmonths()
        
        let firstDayComponents = dateCalendar.components([.era,.year,.month,.day,.weekday], from:dateCalendar.date(from: weakDay)!)
        
        print(firstDayComponents as Any)
        
        let weakDayNext = firstDayComponents.weekday
        
      
        return weakDayNext! - 1
    }
    
    
    
    
    
    
    
    
    //今天计划
    func todayInfo(dateInfo:String) -> Void {
        NetWorkRequest(HomePlanApi.todayPlan(today: dateInfo)) { ResponseModel in
            if ResponseModel.code == 200 {
                self.dateDataSource.removeAll()
                self.dateDataSource.append(contentsOf: Mapper<HomeTodayListModel>().mapArray(JSONString: ResponseModel.dataString) ?? [])
                self.myPlanTableView.reloadData()
            }else {
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    
    @objc func createNavigationPush() -> Void {
        let createPlanVc = MCCreatePlanVc.init()
        self.navigationController?.pushViewController(createPlanVc, animated: true)
    }
    
    @IBAction func addPlanSender(_ sender: UIButton) {
        let addCreatePlanVc = MCAddCreatePlanVc.init()
        self.navigationController?.pushViewController(addCreatePlanVc, animated: true)
    }
    
    @IBAction func createPlanSender(_ sender: UIButton) {
        let createPlanVc = MCCreateNewPlanVc.init()
        self.navigationController?.pushViewController(createPlanVc, animated: true)
    }
    
}

extension MCMyPlanVc:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dateDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCProgressTableCell = tableView.dequeueReusableCell(withIdentifier: myPlanTableViewIdentifier, for: indexPath) as! MCProgressTableCell
       
        let model = dateDataSource[indexPath.row]
        cell.configCell(model: model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = MCSectionHeaderView().initHeaderView()
       
        headerView.titleLab.isHidden = false
        headerView.titleLab.text = self.selectDate
        headerView.timeLabel.isHidden = true
        headerView.enterImageView.isHidden = true
        
        return headerView
    }
    
}


extension MCMyPlanVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: ScreenWidth  / 7, height: 80)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return getDays(section) + self.getweekDay(section: section)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MCMyPlanCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: myPlanCollectionViewIdentifier, for: indexPath) as! MCMyPlanCollectionCell
        if indexPath.row  % 7 == 0 {
            cell.weekNumberLabel.text = "日"
        }else if indexPath.row % 7 == 1 {
            cell.weekNumberLabel.text = "一"
        }else if indexPath.row % 7 == 2 {
            cell.weekNumberLabel.text = "二"
        }else if indexPath.row % 7 == 3 {
            cell.weekNumberLabel.text = "三"
        }else if indexPath.row % 7 == 4 {
            cell.weekNumberLabel.text = "四"
        }else if indexPath.row % 7 == 5 {
            cell.weekNumberLabel.text = "五"
        }else if indexPath.row % 7 == 6 {
            cell.weekNumberLabel.text = "六"
        }else {
            cell.weekNumberLabel.text = ""
        }
        let dateTimeInfo = (indexPath.row - getweekDay(section:indexPath.section)) + 1
        if dateTimeInfo > 0 {
            cell.dateNumberLabel.text = "\(dateTimeInfo)"
            cell.dateNumberLabel.isHidden = false
        }else {
            cell.dateNumberLabel.isHidden = true
        }
         
        cell.changeBgView(selected: indexPath == selectedCollectionItemIndexPath)        
        
        
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectDate = "\(self.getmonths())月\(indexPath.row + 1)日"
        self.todayInfo(dateInfo:"\(self.getYears())-\(self.getmonths())-\(indexPath.row + 1)")
        selectedCollectionItemIndexPath = indexPath
        myPlanCollectionView.reloadData()
    }
}

